package spikemanctrl

import (
	"net/http"
	"time"
	"web_server/model/mainmodel"
	"web_server/model/spikemodel"
	"web_server/utils"

	"github.com/gin-gonic/gin"
)

func SpikeMan(ctx *gin.Context, user mainmodel.UserModel) {
	timenow := time.Now()
	timedateS := timenow.Format("2006-01-02")
	timetod, _ := time.Parse("2006-01-02", timedateS)
	timetom := timetod.Add(time.Hour * 24)
	ctx.HTML(http.StatusOK, "spikeman.html", gin.H{
		"timeb":    timenow.Format("2006-01-02 15:04:05"),
		"timee":    timetom.Format("2006-01-02 15:04:05"),
		"timedate": timedateS,
		"pubkey":   utils.GetPubKeyString(),
	})
}

func SpikeManPost(ctx *gin.Context, user mainmodel.UserModel) {
	action := ctx.Param("action")
	switch action {
	case "/init":
		SpikeManPostInit(ctx, user)
	case "/stat":
		ret := spikemodel.GetSpikeStat()
		if ret == nil {
			ctx.JSON(0, gin.H{
				"status": false,
				"msg":    "系统错误",
			})
		}
		ctx.JSON(http.StatusOK, ret)
	case "/clear":
		ret := spikemodel.GetSpikeClear()
		if ret == nil {
			ctx.JSON(0, gin.H{
				"status": false,
				"msg":    "系统错误",
			})
			return
		}
		ctx.JSON(http.StatusOK, ret)
	default:
		ctx.Status(http.StatusNotFound)
	}
}

func checkTime(tdata string) bool {
	ttime, err := time.Parse("2006-01-02 15:04:05", tdata)
	if err != nil {
		return false
	}
	return tdata == ttime.Format("2006-01-02 15:04:05")
}

func checkDate(tdata string) bool {
	ttime, err := time.Parse("2006-01-02", tdata)
	if err != nil {
		return false
	}
	return tdata == ttime.Format("2006-01-02")
}

func SpikeManPostInit(ctx *gin.Context, user mainmodel.UserModel) {
	r := ctx.Request
	data := r.FormValue("data")
	var jsdata struct {
		Idb   string `json:"b"`
		Ide   string `json:"e"`
		Timeb string `json:"tb"`
		Timee string `json:"te"`
		Timed string `json:"td"`
	}
	if err := utils.B64RsaJsonDecrypt(data, &jsdata); err != nil {
		ctx.JSON(0, gin.H{
			"status": false,
			"msg":    "信息格式错误",
		})
	}
	if len(jsdata.Idb) < 2 || len(jsdata.Idb) > 10 ||
		len(jsdata.Ide) < 2 || len(jsdata.Ide) > 10 ||
		!checkTime(jsdata.Timeb) || !checkTime(jsdata.Timee) || !checkDate(jsdata.Timed) {
		ctx.JSON(0, gin.H{
			"status": false,
			"msg":    "信息格式错误",
		})
		return
	}
	ret := spikemodel.GetSpikeInit(jsdata.Idb, jsdata.Ide, jsdata.Timeb, jsdata.Timee, jsdata.Timed)
	if ret == nil {
		ctx.JSON(0, gin.H{
			"status": false,
			"msg":    "系统错误",
		})
		return
	}
	ctx.JSON(http.StatusOK, ret)
}
